<template>
  <div class="dictionaryCost h100">
    <div class="PageContent">
      <el-col :span="4" class="left-tree">
        <el-tree ref="adminAreaTree"
                 :props="defaultProps"
                 node-key="id"
                 :load="loadNode"
                 lazy
                 highlight-current
                 @node-click="handleCheck"
                 expand-on-click-node="true"
        >
        </el-tree>
      </el-col>
      <el-col :span="20" class="right-tree">
        <el-row style="text-align: left;line-height: 5em;">
          <el-button v-if="btnRight.btnAdminAreaAdd" type="primary" plain @click="addArea()">新增</el-button>
          <el-button v-if="btnRight.btnAdminAreaEdit" type="primary" @click="modifyArea()">修改</el-button>
          <el-button v-if="btnRight.btnAdminAreaDelete" type="danger" @click="deleteArea()">删除</el-button>
        </el-row>
        <el-table
          ref="areaTable" :header-cell-style="{background:'rgb(246,247,251)',color:'#606266'}"
          :data="areaTableData"
          stripe
          border
          @row-click="handleRowClick"
          @select="select" @select-all="selectAll"
          style="width: 100%;height: calc(100% - 140px);overflow-y: scroll">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            property="parentName"
            label="父区划名称"
            align='center'
            width="200">
          </el-table-column>
          <el-table-column
            property="areaCode"
            label="区划编码"
            align='center'
            width="200">
          </el-table-column>
          <el-table-column
            property="areaName"
            label="区划名称"
            align='center'
            width="200">
          </el-table-column>
          <el-table-column
            property="areaNameAbbr"
            align='center'
            label="简拼"
            width="300"
          >
          </el-table-column>
          <el-table-column
            property="disableState"
            align='center'
            label="状态"
          >
            <template slot-scope="{row,$index}">
              <span v-if="row.disableState==0">有效可用</span>
              <span v-else-if="row.disableState==1">无效禁用</span>
            </template>
          </el-table-column>
          <el-table-column property="sort" align='center' label="排序" width="200">
          </el-table-column>
        </el-table>
        <p style="text-align: right;margin-top: 20px;">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pager.currentPage"
            :page-size="pager.pageSize"
            background
            layout="prev, pager, next, jumper"
            :total="pager.total">
          </el-pagination>
        </p>
      </el-col>

    </div>
    <el-dialog title="行政区划数据维护" :visible.sync="dialogAreaVisibleType" width="450px" v-dialogDrag border
               @close="closeDialog()">
      <el-form :model="saveAdminArea" :rules="rules" ref="areaDialog" :inline="true" label-width="120px"
               :disabled="saveFlag">
        <el-row :gutter="5">
          <el-form-item label="父区划:">
            <span>{{saveAdminArea.parentName}}</span>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="区划编码:" prop="areaCode">
            <el-input v-model="saveAdminArea.areaCode" maxlength="50"></el-input>
          </el-form-item>
        </el-row>

        <el-row :gutter="5">
          <el-form-item label="区划名称:" prop="areaName">
            <el-input v-model="saveAdminArea.areaName" :maxlength="50"></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="区划状态:" prop="disableState">
            <el-select v-model="saveAdminArea.disableState" style="width: 185px;" placeholder="请选择" :maxlength="50">
              <el-option
                v-for="item in disableStateData"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="是否省市区县:" prop="asProvinceCityCounty">
            <el-select v-model="saveAdminArea.asProvinceCityCounty" style="width: 185px;" placeholder="请选择" :maxlength="50">
              <el-option
                v-for="item in asProvinceCityCountyData"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="显示顺序:">
            <el-input v-model="saveAdminArea.sort" onkeyup="value= (value.match(/^\d*(\.?\d{0,2})/g)[0]) || null"
                      :maxlength="11"></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="备注:">
            <el-input v-model="saveAdminArea.remark"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: right;">
        <el-button v-if="btnRight.btnAdminAreaSave" type="primary" @click="submit()" :disabled="saveFlag">保存</el-button>
        <el-button v-if="btnRight.btnAdminAreaCancel" type="primary" plain @click="cancelForm()">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import * as API from '@/api/systemApplication'
  import {treeDictionaryformate} from "../../utils/treeDictionaryformate";
  import {validatePass} from '../../utils/validate'

  export default {
    name: "adminArea",
    data() {
      return {
        rules: {
          areaCode: [{required: true, message: '请输入区划编码', trigger: 'blur'}],
          areaName: [{required: true, message: '请输入区划名称', trigger: 'blur'}],
          disableState: [{required: true, message: '请选择区划状态', trigger: 'change', validator: validatePass}],
        },
        treeNode: {},
        treeAreaData: [{
          id: 0,
          label: '中国',
          children: []
        }],
        defaultProps: {
          label: 'label',
          children: 'children'
        },
        selectedParentId: 0,//选中父id
        selectedParentName: "",//选中父名称
        selectedResolve: null,// 加载 Resolve
        areaTableData: [{
          "id": 0,
          "version": 0,
          "parentName": "",
          "parentCode": "",//显文本
          "areaCode": "",//区编码
          "areaName": "",//区名称
          "areaNameAbbr": "",//abbr
          "disableState": 0,//禁用状态
          "asProvinceCityCounty":0,
          "sort": 0, //排序
          "remark": ""//备注
        }],
        //计算规则
        calculateRules: [],
        //禁用状态
        asProvinceCityCountyData: [{
          "label": "街道或村庄",
          "value": 0
        }, {
          "label": "省市区县，即城市",
          "value": 1
        }
        ],
        disableStateData: [{
          "label": "有效可用",
          "value": 0
        }, {
          "label": "无效禁用",
          "value": 1
        }
        ],
        //当前行ss
        currentRow: null,
        tableSelection: [],
        selectedDictionaryId: 0,//选择字典id
        selectedId: 0,//选择字典规明细id
        onpresscTime: 0,  //  阻止短时间内连续点击
        saveFlag: false, //保存标志
        dialogAreaVisibleType: false,  //项目分类维护对话框
        //total总页数，pageSize:每页显示数量，currentPage：当前页
        pager: {
          "pageSize": 20,
          "total": 1,
          "currentPage": 1
        },
        saveAdminArea: {
          //保存行政区划信息
          "id": 0,
          "version": 0,
          "parentName": "",
          "parentCode": "",//显文本
          "areaCode": "",//区编码
          "areaName": "",//区名称
          "areaNameAbbr": "",//abbr
          "disableState": 0,//禁用状态
          "sort": 0, //排序
          "remark": "",//备注
          "asProvinceCityCounty": 0
        },
        btnRight: {
          btnAdminAreaAdd: true, //新增
          btnAdminAreaEdit: true,//修改
          btnAdminAreaDelete: true,//删除
          btnAdminAreaSave: true,//保存
          btnAdminAreaCancel: true,//取消
        }
      }
    },
    created() {
      //载入选中字典类型
      //this.loadNode();
      /* this.loadDictionaryCostList()
       this.treeAreaData.forEach(row => {
         this.idArr.push(row.id)
       })*/

    },
    mounted() {
      //载入选中字典类型
      //this.loadDictionaryCostList()
      //获得菜单按钮
      this.btnRight = this.$route.meta.buttons;
      //遍历属性赋值将true与false字符串转换成布尔型的值
      for (let key of Object.keys(this.btnRight)) {
        this.btnRight[key] = (this.btnRight[key] || this.btnRight[key] == "true") ? true : false;
      }
    },
    methods: {
      //lazy模式下加载
      loadNode(node, resolve) {
        let this_load = this;
        this_load.selectedResolve = resolve;
        this.treeNode = node
        // 初始化第一层
        if (node.level == 0) {
          return resolve(this_load.treeAreaData);
        }

        // 懒加载子数据
        let postData = {id: node.data.id};
        API['loadAdministrativeAreaTreeWithParentId'](postData).then(response => {
          const {data} = response;
          if (!data) {
            this_load.$message('数据读取失败')
            return
          }
          return resolve(data);
        }).catch(error => {
          this_load.$message(error)
        })
      },
      //加载选中字典列表信息
      loadDictionaryCostList(id) {
        //加载行政区划根，根是id->0 名称->中国
        let postData = {
          "id": id,
          "pageSize": this.pager.pageSize,
          "currentPage": this.pager.currentPage,
          "exportExcelFlag": 0,
          "orderField": "id",
          "orderType": "asc"
        }

        let load_this = this;
        API['loadAdministrativeAreaListWithParentId'](postData).then(response => {
          const {data} = response;
          if (!data) {
            load_this.$message('数据读取失败')
            return
          }
          load_this.areaTableData = data.list;
          this.pager = data.pager
        }).catch(error => {
          // load_this.$message(error)
        })
      }, change(val) {
        val = val.replace(/(^\s*)|(\s*$)/g, "")
        if (!val) {
          this.saveAdminArea.dataCode = "";
          return
        }
        let reg = /[^\d]/g
        // 只能是数字和小数点，不能是其他输入
        val = val.replace(reg, "")
        this.saveAdminArea.dataCode = val;
      },//新增
      addArea() {
        let parentId = this.selectedParentId;
        let this_add = this;
        //查询父级节点的code
        let postData = {
          "id": parentId
        }
        //载入字典明细
        API['loadAdministrativeAreaWithId'](postData).then(response => {
          let data = response;
          if (!data) {
            this_add.$message(data.message);
            return
          } else {
            this_add.saveAdminArea = data.data;
            let parentCode = data.data.areaCode;
            let parentName = data.data.areaName;
            let parentId = data.data.id;
            this_add.saveAdminArea = {
              //保存行政区划信息
              "id": 0,
              "version": 0,
              "parentName": parentName,//父区划名称
              "parentCode": parentCode,//显文本
              "areaCode": "",//区编码
              "areaName": "",//区名称
              "areaNameAbbr": "",//abbr
              "disableState": 0,//禁用状态
              "asProvinceCityCounty" :0,
              "sort": 0, //排序
              "remark": ""//备注
            }
            //父id
            this_add.saveAdminArea.parentId = parentId;
            this_add.dialogAreaVisibleType = true;
          }
        }).catch(error => {
          // this.$message(error);
        })

      },
      //明细修改
      modifyArea() {
        this.saveAdminArea = {
          //保存行政区划信息
          "id": 0,
          "version": 0,
          "parentName": "",
          "parentCode": "",//显文本
          "areaCode": "",//区编码
          "areaName": "",//区名称
          "areaNameAbbr": "",//abbr
          "disableState": 0,//禁用状态
          "asProvinceCityCounty":0,
          "sort": 0, //排序
          "remark": ""//备注
        }
        let data = this.tableSelection;
        let item = null;
        let this_modify = this;
        if (data && data.length > 0) {
          item = data[0];
        } else {
          return;
        }
        let postData = {
          "id": item.id
        }
        //载入字典明细
        API['loadAdministrativeAreaWithId'](postData).then(response => {
          let data = response;
          if (!data) {
            this.$message(data.message);
            return
          } else {
            this_modify.saveAdminArea = data.data;
            this_modify.dialogAreaVisibleType = true;
          }

        }).catch(error => {
          // this.$message(error);
        })
      },
      // 初始页currentPage、初始每页数据数pagesize和数据data
      handleSizeChange: function (size) {
        this.pager.pagesize = size;
        alert(pagesize)  //每页下拉显示数据
      },
      handleCurrentChange: function (currentPage) {
        this.pager.currentPage = currentPage;
        this.loadDictionaryCostList(this.selectedParentId);  //点击第几页加载数据
      },
      closeDialog() {
        this.dialogAreaVisibleType = false;
      },//根据明细id删除明细数据
      deleteArea() {
        let data = this.tableSelection;
        let postData = []
        if (data && data.length > 0) {
          this.$confirm('删除信息, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            data.forEach(item => {
              postData.push({
                "id": item.id,
                "version": item.version
              })
            })

            let this_del = this;
            //载入字典明细
            API['deleteAdministrativeAreaWithId'](postData).then(response => {
              let data = response;
              if (!data) {
                this_del.$message(data.message)
                return
              } else {
                this.tableSelection = []
                this_del.$message(data.message)
              }
              //加载data
              //加载选中节点子列表
              this_del.loadDictionaryCostList(this_del.selectedParentId);
              this.loadNode(this.treeNode, this.selectedResolve)

            }).catch(error => {
              this_del.$message(error)
            })
          }).catch(() => {
            //几点取消的提示
          });
        }
      },
      //tree单选
      handleCheck(data, checked, node) {
        let id = data.id;
        //选中父编号
        this.selectedParentId = data.id;
        this.selectedParentName = data.label;
        /*清空表格*/
        this.tableSelection = []
        this.loadDictionaryCostList(id);
      },
      //点击行触发，选中或不选中复选框
      handleRowClick(row, column, event) {
        if (this.tableSelection.length > 0) {
          this.$refs.areaTable.toggleRowSelection(this.tableSelection[0], false);
        }
        this.$refs.areaTable.toggleRowSelection(row);
        this.tableSelection = [row]
      },
      select(selection, row) {
        // 选择项大于1时
        if (selection.length > 1) {
          let del_row = selection.shift();
          // console.log('把数组的第一个元素从其中删除后', selection);
          this.$refs.areaTable.toggleRowSelection(del_row, false); // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
        }
        this.tableSelection = selection;
        //选择serviceItemId->id
        this.selectedId = row.serviceItemId;
        this.selectedDictionaryId = row.dataDictionaryId;
      },
      selectAll(selection) {
        if (selection.length > 1) {
          selection.length = 1;
        }
        this.tableSelection = selection
      },
      //字典费用规则保存
      submit() {
        if (this.saveFlag) {
          this.$message("正在保存中请稍后再试")
          return
        }
        this.$refs.areaDialog.validate(valid => {
          if (valid) {
            this.saveAdminArea.asProvinceCityCounty = 0;

            let postData = this.saveAdminArea;
            let this_submit = this;
            this.saveFlag = true
            API['saveAdministrativeArea'](this.saveAdminArea).then(response => {
              if (response) {
                let data = response;
                if (!data) {
                  this.saveFlag = false;
                  this.$message('数据保存失败')
                  return
                }
                this_submit.dialogAreaVisibleType = false;
                //加载选中节点子列表
                this_submit.loadDictionaryCostList(this_submit.selectedParentId);
                this.loadNode(this.treeNode, this.selectedResolve)
              } else {
                this.$message('数据保存失败')
              }
              this.saveFlag = false
            }).catch(error => {
              // this.$message(error)
              this.saveFlag = false
            })
          }
        })
      },//取消
      cancelForm() {
        this.dialogAreaVisibleType = false
      }

    },
    watch: {
      "dialogAreaVisibleType"() {
        if (this.dialogAreaVisibleType == false) {
          this.$nextTick(() => {
            this.$refs.areaDialog.resetFields();
          })
        }
      }
    }
  }
</script>

<style scoped>

</style>
